<template>
	<el-dialog custom-class="checkbox-group-dialog" :visible="visible" :width="width" :before-close="cancelCheckedChange" @open="opening">
		<template v-slot:title>
			选择列
			<el-checkbox v-model="checkAll" @change="handleCheckedItemsChange"></el-checkbox>
		</template>
		<div class="dialog-content">
			<div class="checkbox-group">
				<el-checkbox-group v-model="value" @change="handleCheckboxChange">
					<el-checkbox v-for="item in items" :label="item[labelProp]" :key="item[labelProp]">{{ item[valueProp]}}</el-checkbox>
				</el-checkbox-group>
			</div>
		</div>
		<template v-slot:footer>
			<span class="dialog-footer">
			<el-button size="mini" @click="cancelCheckedChange">取 消</el-button>
			<el-button size="mini" type="primary" @click="submitCheckedChange">确 定</el-button>
		</span>
		</template>
	</el-dialog>
</template>

<script>
export default {
	name: "CheckboxGroupDialog",
	props: {
		width: String,
		visible: {
			type: Boolean,
			default: false
		},
		labelProp: String,	// checkbox value
		valueProp: String,	// checkbox view
		items: {
			type: Array,
			default: () => []	// String/Object Array
		},
		checkedItems: {
			type: Array,
			default: () => []	// String Array
		}
	},
	data() {
		return {
			checkAll: false,
			value: this.checkedItems
		}
	},
	computed: {
		itemsLabelMap() {
			return this.items.map(item => item[this.labelProp])
		}
	},
	methods: {
		handleCheckedItemsChange(val) {
			this.value = val ? this.itemsLabelMap : []
		},
		handleCheckboxChange() {
			this.checkAll = this.items.length === this.value.length
		},
		cancelCheckedChange() {
			this.value = this.checkedItems;
			this.closeDialog();
		},
		submitCheckedChange() {
			this.$emit("change", this.value)
			this.closeDialog()
		},
		opening() {
			this.checkAll = this.items.length === this.checkedItems.length;
		},
		closeDialog() {
			this.$emit("update:visible", false)
		}
	}
}
</script>

<style lang="scss">
.checkbox-group-dialog {
	.el-dialog__header {
		//border-bottom: 1px solid #eee;
	}
	.dialog-content .el-checkbox {
		line-height: 28px;
		.el-checkbox__label {
			width: 60px!important;
			display: inline-block;
			white-space: nowrap;
			text-overflow: ellipsis;
			overflow: hidden;
			vertical-align: middle;
		}
	}
}
</style>
